<!-- 团购商品 -->
<template>
  <div>
    <!-- 查找 -->
    <el-space wrap>
      <el-input v-model="refTrade.refTradename" placeholder="请输入商品名称" />
      <el-input v-model="refTrade.refProductid" placeholder="请输入团购ID" />
      <el-select v-model="refTrade.refProductstatus" placeholder="请选择团购状态">
        <el-option v-for="item in refStatusgroup" :key="item.value" :label="item.name" :value="item.value"></el-option>
      </el-select>
      <el-button type="primary" :icon="Search" @click="handlelookup">查找</el-button>
      <el-button type="primary" :icon="Search" @click="handleadd">添加</el-button>
    </el-space>
  </div>

  <!-- 表格 -->
  <div style="margin-top: 20px;">
    <el-table v-loading="loading" :data="tableData" border style="width:100%" row-key="id" :default-expand-all="false">
      <el-table-column type="expand" align="center">
        <!-- 嵌套商品数据 -->
        <template #default="props">
          <el-descriptions direction='horizontal' :column="1" border>
            <el-descriptions-item label="类目ID" label-class-name="my-label" class-name="my-content" align="center">
              {{ props.row.categoryId }}
            </el-descriptions-item>
            <el-descriptions-item label="商品sku属性" width="105px" align="center">
              <el-table :data="props.row.groupShopSkuDTOList" :default-expand-all='true' border style="width: 100%">
                <el-table-column prop="skuId" label="SKuID" width="100px" align="center" />
                <el-table-column prop="title" label="规格标题" align="center" />
                <el-table-column prop="skuGroupShopPrice" label="团购价格(元)" width="110px" align="center" />
                <el-table-column prop="stock" label="库存" width="100px" align="center">
                  <template #default="scope">{{scope.row.stock}}(件)</template>
                </el-table-column>
                <el-table-column prop="originalPrice" label="原始价格(元)" width="110px" align="center" />
                <el-table-column prop="price" label="售卖价格(元)" align="center" />
                <el-table-column prop="vipPrice" label="会员价格(元)" align="center" />
                <el-table-column prop="barCode" label="国际条码" align="center" />
              </el-table>
            </el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column label="团购ID" prop="id" align="center" width="auto" />
      <el-table-column label="商品ID" prop="spuId" align="center" width="auto" />
      <el-table-column label="商品名称" prop="title" align="center" width="300px" />
      <el-table-column label="商品主图" align="center" width="auto">
        <!-- 图片放大弹出框 -->
        <template #default="scope">
          <el-popover placement="right" width="auto">
            <template #reference>
              <img :src="scope.row.img" mode="heightFix" style="width:100%;" />
            </template>
            <template #default>
              <img :src="scope.row.img" mode="heightFix" style="width: 100%;height:200px;" />
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="未满策略" prop="automaticRefund" align="center" width="auto">
        <template #default="scope">
          <el-tag :type="scope.row.automaticRefund==0?'warning':'success'">{{scope.row.automaticRefund==0?'发货':'退款'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" prop="status" align="center" width="auto">
        <template #default="scope">
          <el-tag :type="scope.row.status==0?'':'success'">{{scope.row.status==0?'冻结':'进行'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" width="auto">
        <template #default="scope">{{ scope.row.gmtStart ? new Date(scope.row.gmtStart).concessionalRate() :'-'
        }}</template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" width="auto">
        <template #default="scope">{{ scope.row.gmtEnd ? new Date(scope.row.gmtEnd).concessionalRate() :'-'
        }}</template>
      </el-table-column>
      <el-table-column label="当前人数" prop="sales" align="center" width="auto" />
      <el-table-column label="目标人数" prop="minNum" align="center" width="auto" />
      <el-table-column label="操作" align="center" width="200%">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handledelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页组件 -->
  <PagingList @Change="giterList" :listdata="listdata"></PagingList>

  <!-- 弹出框窗口 -->
  <el-drawer v-model="drawer2" size="50%" direction="ltr" :show-close='false'>
    <template #title>
      <span>{{reftitle=='创建'?'创建团购商品':'编辑团购商品'}}</span>
      <div style="flex:right">
        <el-button @click="drawer2= false">取消</el-button>
        <el-button type="primary" @click="reftitle=='创建'?handleCreate():handleEditgroup()">{{reftitle=='创建'?'创建':'编辑'}}
        </el-button>
      </div>
    </template>
    <template #default>
      <el-card>
        <h4>商品团购属性(spu)</h4>
        <el-form :model="form" label-width="120px">
          <el-form-item label="团购商品">
            <el-cascader :options="refcommodity" v-model="form.spuId" :props="goodsProps" clearable placeholder="团购商品"
              @change="handlechangeSku" />
          </el-form-item>
          <el-form-item label="团购时间">
            <el-config-provider :locale="locale">
              <el-date-picker v-model="form.gmtStart" value-format="x" type="datetime" placeholder="选择开始日期" />
              至
              <el-date-picker v-model="form.gmtEnd" format='YYYY-MM-DD' value-format="x" type="datetime"
                placeholder="选择结束日期" />
            </el-config-provider>
          </el-form-item>
          <el-form-item label="团购基础人数">
            <el-input-number v-model="form.minNum" :min="1" :step="1" step-strictly controls-position="right" />
          </el-form-item>
          <el-form-item label="活动结束时人数没有达到基础人数采取">
            <el-radio-group v-model="form.automaticRefund">
              <el-radio-button :label="0">不退款,我要发货</el-radio-button>
              <el-radio-button :label="1">自动退款,我不发货</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 商品类型 -->
      <el-card>
        <template #header>
          <div class="card_haerder">
            <span>商品类型(sku)</span>
            <el-popover ref="popover" placement="right" :width="400" trigger="click"
              content="this is content, this is content, this is content">
              <template #reference>
                <el-button type="primary" plain @click="visible = true" v-if="refCommoditytype!= 0">批量定价
                </el-button>
              </template>
              <el-form label-position="right" label-width="115px" style="max-width: 290px">
                <el-form-item label="团购价格">
                  <el-input-number v-model="refGroupPiece" :min="1" :step="1" controls-position="right" />
                  <span style="padding-left: 10px;">元</span>
                </el-form-item>
                <el-form-item>
                  <el-button @click="$refs.popover?.hide?.()">取消</el-button>
                  <el-button type="primary" @click="handleSkuPiece">确定</el-button>
                </el-form-item>
              </el-form>
            </el-popover>
          </div>
        </template>
        <el-table :data="refCommoditytype" style="width:100%">
          <el-table-column prop="id" label="SkuId" />
          <el-table-column prop="barCode" label="Sku条形码" />
          <el-table-column prop="title" label="类型名" />
          <el-table-column prop="stock" label="库存">
            <template #default="scope">
              <span>{{scope.row.stock}}</span>
            </template>
          </el-table-column>
          <el-table-column label="现价/元">
            <template #default="scope">
              <span>{{scope.row.price}}</span>
            </template>
          </el-table-column>
          <el-table-column label="团购价格/元">
            <template #default="scope">
              <span>{{scope.row.skuGroupShopPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" @click="handletoupdate(scope.$index,scope.row)">更新</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 更新窗口 -->
      <el-dialog v-model="dialogFormVisible" title="更新团购价格">
        <el-form :model="refskuGroup">
          <el-form-item label="团购价格">
            <el-input-number v-model="refskuGroup.grouppurchaseprice" :min="1" :step="1" controls-position="right" />
          </el-form-item>
          <el-form-item label="现价">
            <span>{{refskuGroup.price}}</span>
          </el-form-item>
          <el-form-item label="sku类型名">
            <span>{{refskuGroup.title}}</span>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleUpdatecomplete">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </template>
  </el-drawer>

</template>

<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { PageGrouppurchase, Typepurchase, Typetabledata, TypeDetail } from "#/index";
import { post } from "@/utils/request";
import { ref, reactive } from 'vue'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'//国际语言


let refgroupIndex = ref(0) //选择的团购商品下标
const popover = ref(null)//控制批量定价的显示和隐藏
const refskuGroup = reactive({
  grouppurchaseprice: 0,// 团购价格
  price: 0,//现价格
  title: ""//标题名称
})
const refGroupPiece = ref(1)//团购价格
const visible = ref(false) //控制批量定价的显示隐藏
const dialogFormVisible = ref(false)//控制更新弹出框的显示和隐藏
const goodsProps = reactive({
  value: "id",
  emitPath: false,
})
const locale = zhCn //中文
let form = reactive({ //表单绑定数据
  gmtStart: '',
  gmtEnd: '',
  minNum: 1,
  automaticRefund: 0,
  spuId: ''
})
const reftitle = ref('')//窗口的title名称
const drawer2 = ref(false)//控制的窗口的显示和隐藏
const refStatusgroup = reactive([{ name: '冻结', value: 0 }, { name: '进行', value: 1 }, { name: '全部', value: '' }])
const refTrade = reactive({
  refTradename: '',//商品名称
  refProductid: null,//商品id
  refProductstatus: null//商品状态
})
const tableData: Typetabledata[] = reactive([]) //表格数据

let refcommodity: TypeDetail[] = reactive([])//商品信息
let refCommoditytype: Typepurchase[] = reactive([]) //商品类型
const loading = ref(true) //控制表格的渲染赖加载
//分页数据
let listdata = reactive(new PageGrouppurchase());
//获取下一页的数据并赋值
const giterList = (e: { page: number; limit: number; total: number; flog: { valueOf: () => boolean }; targetAdminId?: undefined; }) => {
  listdata = e;
  handlelist();
};
let refempty = { ...form }//清空

/**
 * 初始化数据
 */
function handlelist() {
  let data = {
    _gp: 'admin.groupshop',
    _mt: 'list',
    id: listdata.id,
    spuName: listdata.spuName,
    status: listdata.status,
    page: listdata.page,
    limit: listdata.limit,
  }
  post(data).then(res => {
    let { data } = res
    tableData.length = 0
    tableData.push(...data.items)
    listdata.total = data.total
    loading.value = false
  })
}
handlelist()

/**
 * 获取商品信息
 */
function handleProductinfo() {
  let data = {
    _gp: 'admin.product',
    _mt: 'getSpuBigTree',
  }
  post(data).then(res => {
    refcommodity.length = 0
    refcommodity.push(...res.data)
  })
}

/**
 * 获取商品类型
 */
function handlechangeSku() {
  let data = {
    _gp: 'admin.product',
    _mt: 'detail',
    spuId: form.spuId
  }
  post(data).then(res => {
    refCommoditytype.length = 0
    refCommoditytype.push(...res.data.skuList)
  })
}

/**
 * 改变团购商品全部价格
 */
function handleSkuPiece() {
  if (!refGroupPiece.value) {
    return ElMessage.error("团购价不能为空")
  } else if (refGroupPiece.value > refCommoditytype[0].price) {
    return ElMessage.error('团购价不能大于现价')
  }
  if (refCommoditytype.length != 0) {
    refCommoditytype.forEach((item) => {
      item.skuGroupShopPrice = refGroupPiece.value
    })
  }
  popover.value?.hide?.()
}
/**
 * 点击更新赋值
 */
function handletoupdate(index: number, row: object) {
  dialogFormVisible.value = true
  refgroupIndex.value = index
  Object.assign(refskuGroup, row)
}


/**
 * 点击当前行赋值更新
 */
function handleUpdatecomplete() {
  refCommoditytype[refgroupIndex.value].skuGroupShopPrice = refskuGroup.grouppurchaseprice
  dialogFormVisible.value = false
}


/**
 * 开启窗口将需要的数据赋值
 */
function handleadd() {
  reftitle.value = "创建"
  drawer2.value = true
  handleProductinfo()
  Object.assign(form, refempty)
  refCommoditytype.length = 0
}

/**
 * 添加表格数据
 */
function handleCreate() {
  if(form.gmtEnd<form.gmtStart){
    return ElMessage.warning('结束时间不能小于开始时间')
  }
  let data = {
    _gp: 'admin.groupshop',
    _mt: 'create',
    ...form,
    groupShopSkuList: JSON.stringify(refCommoditytype.map((item) => ({
      skuId: item.id,// SkuId
      skuGroupShopPrice: item.skuGroupShopPrice// 团购价格
    })))
  }
  post(data).then(res => {
    let { errno, errmsg } = res
    if (200 == errno) {
      handlelist()
      drawer2.value = false
      ElMessage.success("恭喜你添加成功")
    }else{
      ElMessage.error(errmsg)
    }
  })
}

/**
 * 打开编辑窗口并赋值
 */
function handleEdit(row: {
  id: string; groupShopSkuDTOList: Typepurchase[]
}) {
  drawer2.value = true
  reftitle.value = '编辑'
  handleProductinfo()
  Object.assign(form, row)
  console.log(row);
  refCommoditytype.length = 0
  refCommoditytype.push(...row.groupShopSkuDTOList)
}

/**
 * 编辑表格信息
 */
function handleEditgroup() {
  let data = {
    _gp: 'admin.groupshop',
    _mt: 'edit',
    ...form,
    groupShopSkuList: JSON.stringify(refCommoditytype.map((item) => ({
      skuId: item.id,// SkuId
      skuGroupShopPrice: item.skuGroupShopPrice// 团购价格
    })))
  }
  post(data).then(res => {
    console.log(res);
    let { errno, errmsg } = res
    if (200 == errno) {
      handlelist()
      drawer2.value = false
      ElMessage.success("恭喜你编辑成功")
    }else{
      ElMessage.error(errmsg)
    }
  })
}


/**
 * 删除表格数据
 */
function handledelete(row: { id: number }) {
  ElMessageBox.confirm(
    '代理将永久删除该文件!',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let data = {
        _gp: 'admin.groupshop',
        _mt: 'delete',
        id: row.id
      }
      post(data).then(res => {
        let { errno, errmsg } = res
        if (200 == errno) {
          ElMessage({
            type: 'success',
            message: '恭喜删除成功！',
          })
          handlelist()
        }else{
          ElMessage.error(errmsg)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除已取消',
      })
    })
}



/**
 * 根据条件查找数据
 */
function handlelookup() {
  listdata.id = refTrade.refProductid
  listdata.spuName = refTrade.refTradename
  listdata.status = refTrade.refProductstatus
  handlelist()
}
</script>

<style lang="less" scoped>
.card_haerder {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    font-size: 14px;
    font-weight: bold;
  }
}
</style>